package com.markerhub.service.impl;

import cn.hutool.core.date.DateTime;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.ObjectMetadata;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.markerhub.common.ContentType;
import com.markerhub.common.lang.Result;
import com.markerhub.config.AliConfig;
import com.markerhub.entity.Notice;
import com.markerhub.entity.VisitsRecord;
import com.markerhub.mapper.NoticeMapper;
import com.markerhub.service.NoticeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.markerhub.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.InputStream;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author MarkerHub
 * @since 2022-04-20
 */
@Slf4j
@Service
public class NoticeServiceImpl extends ServiceImpl<NoticeMapper, Notice> implements NoticeService {
    @Value("${file.dir}")
    private String realpath;
    @Autowired
    NoticeMapper noticeMapper;
    @Autowired
    RedisUtil redisUtil;

    @Override
    public Result updateNotice(Notice notice, MultipartFile multipartFile) {
        String url = "";
        log.info("公告信息: [{}]", notice.toString());
        if (multipartFile != null) {
            MultipartFile file = multipartFile;
            log.info("文件名: [{}]", file.getOriginalFilename());
            // yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1（杭州）为例，Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
            String endpoint = AliConfig.END_POINT;
            // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
            String accessKeyId = AliConfig.ACCESS_KEY_ID;
            String accessKeySecret = AliConfig.ACCESS_KEY_SECRET;
            String bucketName = AliConfig.BUCKET_NAME;
            String folder = AliConfig.FOLDER;
            try {
                // 创建OSSClient实例。
                OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
                // 填写本地文件的完整路径。如果未指定本地路径，则默认从示例程序所属项目对应本地路径中上传文件流。
                InputStream inputStream = file.getInputStream();
                //获取文件真实名称
                String originalFilename = file.getOriginalFilename();
                //重命名，防止相同文件出现覆盖
                //生成的f4f2e1a3-391a-4d5a-9438-0c9f5d27708c 需要替换成 f4f2e1a3391a4d5a94380c9f5d27708c
                String uuid = UUID.randomUUID().toString().replaceAll("-", "");
                //新的文件名
                originalFilename = uuid + originalFilename;
                //2、把文件按照日期进行分类
                String datePath = new DateTime().toString("yyyy/MM/dd");
                //拼接
                originalFilename = folder + "/" + datePath + "/" + originalFilename;
                // oss实现上传文件
                ObjectMetadata objectMetadata = new ObjectMetadata();
                objectMetadata.setContentType(ContentType.getcontentType(originalFilename.substring(originalFilename.lastIndexOf("."))));
                ossClient.putObject(bucketName, originalFilename, inputStream, objectMetadata);
                // 关闭OSSClient
                ossClient.shutdown();
                //拼接url
                url = "https://" + bucketName + "." + endpoint + "/" + originalFilename;

            } catch (Exception e) {
                e.printStackTrace();

            }
        }
        try {
            Notice notice1 = new Notice();
            if (multipartFile != null)
                notice1.setDocuments(url);
            notice1.setTitle(notice.getTitle());
            notice1.setContent(notice.getContent());
            noticeMapper.update(notice1, new UpdateWrapper<Notice>().eq("id", notice.getId()));
        } catch (Exception exception) {
            exception.printStackTrace();
            return Result.fail("更新失败");
        }
        return Result.succ("更新成功");
    }

    @Override
    public List<Notice> getNoticeList() {

        return noticeMapper.getNoticeList();
    }

    @Override
    public Result noticePublish(Notice notice, MultipartFile multipartFile) {

        String url = "";
        log.info("公告信息: [{}]", notice.toString());
        if (multipartFile != null) {
            MultipartFile file = multipartFile;
            log.info("文件名: [{}]", file.getOriginalFilename());
            // yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1（杭州）为例，Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
            String endpoint = AliConfig.END_POINT;
            // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
            String accessKeyId = AliConfig.ACCESS_KEY_ID;
            String accessKeySecret = AliConfig.ACCESS_KEY_SECRET;
            String bucketName = AliConfig.BUCKET_NAME;
            String folder = AliConfig.FOLDER;
            try {
                // 创建OSSClient实例。
                OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
                // 填写本地文件的完整路径。如果未指定本地路径，则默认从示例程序所属项目对应本地路径中上传文件流。
                InputStream inputStream = file.getInputStream();
                //获取文件真实名称
                String originalFilename = file.getOriginalFilename();
                //重命名，防止相同文件出现覆盖
                //生成的f4f2e1a3-391a-4d5a-9438-0c9f5d27708c 需要替换成 f4f2e1a3391a4d5a94380c9f5d27708c
                String uuid = UUID.randomUUID().toString().replaceAll("-", "");
                //新的文件名
                originalFilename = uuid + originalFilename;
                //2、把文件按照日期进行分类
                String datePath = new DateTime().toString("yyyy/MM/dd");
                //拼接
                originalFilename = folder + "/" + datePath + "/" + originalFilename;
                // oss实现上传文件
                ObjectMetadata objectMetadata = new ObjectMetadata();
                objectMetadata.setContentType(ContentType.getcontentType(originalFilename.substring(originalFilename.lastIndexOf("."))));
                ossClient.putObject(bucketName, originalFilename, inputStream, objectMetadata);
                // 关闭OSSClient
                ossClient.shutdown();
                //拼接url
                url = "https://" + bucketName + "." + endpoint + "/" + originalFilename;

            } catch (Exception e) {
                e.printStackTrace();

            }
        }
        try {
            String publishtime = String.format("%tF", new Date());
            notice.setTime(publishtime);
            notice.setDocuments(url);
            noticeMapper.insert(notice);
        } catch (Exception exception) {
            exception.printStackTrace();
            return Result.fail("发布失败");
        }
        return Result.succ("发布成功");
    }

}

